/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package filetransfer;

import bmechat.client.Client;
import java.net.*;
import java.io.*;

/**
 *
 * @author Owner
 */
public class FileServer implements Runnable {

    String args[];
    Client client;

    public FileServer(String[] args, Client client) {
        this.args = args;
        this.client = client;
    }

    public void run() {
        try {
            // create socket
            ServerSocket servsock = new ServerSocket(16689);
            FileInputStream fis = null;

            Socket sock = servsock.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));

            // sendfile
            File myFile = new File(args[0]);
            byte[] mybytearray = new byte[(int) myFile.length()];
            fis = new FileInputStream(myFile);
            BufferedInputStream bis = new BufferedInputStream(fis);
            bis.read(mybytearray, 0, mybytearray.length);
            OutputStream os = sock.getOutputStream();
            os.write(mybytearray, 0, mybytearray.length);
            os.flush();
            client.addToChatLog("File sent");
            fis.close();
            sock.close();

        } catch (IOException ex) {
            client.addToChatLog("File transfer failed.");
            System.out.println(ex.getMessage());
        }
    }
}
